package org.dromara.business.modules.contactForm.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.validation.constraints.NotEmpty;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.business.modules.contactForm.domain.BuContactForm;
import org.dromara.business.modules.contactForm.domain.bo.BuContactFormBo;
import org.dromara.business.modules.contactForm.domain.vo.BuContactFormVo;
import org.dromara.business.modules.contactForm.mapper.BuContactFormMapper;
import org.dromara.business.modules.contactForm.service.IBuContactFormService;
import org.dromara.business.modules.demands.mapper.BuDemandsMapper;
import org.dromara.business.modules.merchant.domain.BuMerchant;
import org.dromara.business.modules.merchant.mapper.BuMerchantMapper;
import org.dromara.business.modules.message.domain.BuMessage;
import org.dromara.business.modules.message.mapper.BuMessageMapper;
import org.dromara.business.modules.services.mapper.BuServicesMapper;
import org.dromara.common.core.constant.RoleConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.UserService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 联系消息Service业务层处理
 *
 * @author ckk
 * @date 2025-11-05
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class BuContactFormServiceImpl implements IBuContactFormService {

    private final BuContactFormMapper baseMapper;
    private final BuDemandsMapper demandsMapper;
    private final BuServicesMapper servicesMapper;
    private final BuMerchantMapper merchantMapper;
    private final UserService userService;
    private final BuMessageMapper messageMapper;

    /**
     * 查询联系消息
     *
     * @param id 主键
     * @return 联系消息
     */
    @Override
    public BuContactFormVo queryById(Long id) {
        BuContactFormVo vo = baseMapper.selectVoById(id);
        Assert.notNull(vo, () -> new ServiceException("数据不存在"));

        if (vo.getCategory() == 0) {
            vo.setDemands(demandsMapper.selectVoById(vo.getRelatedId()));
        } else {
            vo.setServices(servicesMapper.selectVoById(vo.getRelatedId()));
        }

        vo.setMerchant(merchantMapper.selectVoOne(Wrappers.lambdaQuery(BuMerchant.class).eq(BuMerchant::getCreateBy, vo.getCreateBy())));
        return vo;
    }

    /**
     * 分页查询联系消息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 联系消息分页列表
     */
    @Override
    public TableDataInfo<BuContactFormVo> queryPageList(BuContactFormBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BuContactForm> lqw = buildQueryWrapper(bo);
        Page<BuContactFormVo> result = baseMapper.queryPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的联系消息列表
     *
     * @param bo 查询条件
     * @return 联系消息列表
     */
    @Override
    public List<BuContactFormVo> queryList(BuContactFormBo bo) {
        LambdaQueryWrapper<BuContactForm> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BuContactForm> buildQueryWrapper(BuContactFormBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BuContactForm> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(BuContactForm::getId);
        lqw.eq(bo.getCategory() != null, BuContactForm::getCategory, bo.getCategory());
        lqw.eq(bo.getRelatedId() != null, BuContactForm::getRelatedId, bo.getRelatedId());
        lqw.eq(StringUtils.isNotBlank(bo.getContactContent()), BuContactForm::getContactContent, bo.getContactContent());
        lqw.eq(StringUtils.isNotBlank(bo.getAttachment()), BuContactForm::getAttachment, bo.getAttachment());
        lqw.eq(StringUtils.isNotBlank(bo.getContactPerson()), BuContactForm::getContactPerson, bo.getContactPerson());
        lqw.eq(StringUtils.isNotBlank(bo.getContactPhone()), BuContactForm::getContactPhone, bo.getContactPhone());
        lqw.eq(bo.getHasRead() != null, BuContactForm::getHasRead, bo.getHasRead());
        return lqw;
    }

    /**
     * 新增联系消息
     *
     * @param bo 联系消息
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(BuContactFormBo bo) {
        BuContactForm add = MapstructUtils.convert(bo, BuContactForm.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());

            List<Long> userIds = userService.selectUserIdsByRoleIds(List.of(RoleConstants.ADMIN));
            String title = "【新咨询】用户 " + bo.getContactPerson() + "（" + bo.getContactPhone() + "）提交咨询，请及时跟进。";
            // 发送站内信
            SseMessageDto dto = new SseMessageDto();
            dto.setMessage(title);
            dto.setUserIds(userIds);
            SseMessageUtils.publishMessage(dto);

            userIds.forEach(userId -> {
                BuMessage buMessage = new BuMessage();
                buMessage.setReceiverId(userId);
                buMessage.setTitle(title);
                buMessage.setIsRead(0);
                buMessage.setIsDeleted(0);
                buMessage.setSendTime(new Date());
                if (bo.getCategory() == 0) {
                    buMessage.setBusinessSign("demand");
                } else if (bo.getCategory() == 1){
                    buMessage.setBusinessSign("service");
                }
                messageMapper.insert(buMessage);
            });
        }
        return flag;
    }

    /**
     * 修改联系消息
     *
     * @param bo 联系消息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BuContactFormBo bo) {
        BuContactForm update = MapstructUtils.convert(bo, BuContactForm.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BuContactForm entity) {
        entity.setHasRead(0);
    }

    /**
     * 校验并批量删除联系消息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteWithValidByIds(ids) > 0;
    }

    @Override
    public Boolean batchRead(List<@NotEmpty(message = "主键不能为空") Long> ids) {
        return new LambdaUpdateChainWrapper<>(baseMapper)
            .set(BuContactForm::getHasRead, 1)
            .in(BuContactForm::getId, ids)
            .update();

    }
}
